# Author: Yu Bin
# Date: 2024/12/31 10:38:11
# E-mail: 853823259@qq.com
import os


def open_r():
    """
    读取文件
    :return:
    """
    file = open('file2.txt', mode='r+', encoding='utf-8')
    text = file.read()  # 读出来的都是字符串
    print(text)
    file.write("world")  # 写到末尾
    text = file.read()
    print(text)
    file.close()


def use_readline():
    file = open("README")
    while True:
        text = file.readline()
        if not text:
            break
        print(text, end="")
    file.close()


def seek_start():
    """
    相对于开头进行偏移
    :return:
    """
    file = open('file2.txt', mode='r+', encoding='utf8')
    file.seek(0, os.SEEK_SET)  # 相对于开头偏移n个字节，汉字的偏移是3的整数倍
    text = file.read(5)
    print(text)
    file.close()


def seek_b_cur():
    """
    在b模式下，读取到的是字节流
    :return:
    """
    file = open('file2.txt', mode='rb+')
    file.seek(5, os.SEEK_CUR)
    file.seek(-2, os.SEEK_CUR)
    file.seek(-2, os.SEEK_END)
    b = file.read()
    print(b)
    file.close()


def copy_file():
    file1 = open("证件照.jpg", mode='rb+')
    file2 = open("copy.jpg", mode='wb+')
    b = file1.read()
    file2.write(b)
    file1.close()
    file2.close()


def modify_movie():  # 未完成
    file1 = open("证件照.jpg", mode='rb+')
    file1.seek(10, os.SEEK_SET)
    byte_value = b[0]  # b 是字节对象，使用 b[0] 获取它的整数值
    inverted_byte = ~byte_value & 0xFF
    print(f"原始字节: {byte_value}, 取反后的字节: {inverted_byte}")
    b = file1.read(1)
    print(b)


def use_rename():
    os.rename('file2.txt', 'file3')


def use_dir_func():
    file_list = os.listdir('.')
    print(file_list)
    os.mkdir('dir2')
    os.rmdir('dir1')
    print((os.getcwd()))


def scan_dir(current_path, width):
    """
    深度优先遍历
    :param current_path:
    :return:
    """
    file_list = os.listdir(current_path)  # 得到当前文件夹下所有文件
    for file in file_list:
        print(' ' * width, file)  # 打印文件名
        if os.path.isdir(file):
            scan_dir(file, width + 4)


if __name__ == '__main__':
    # open_r()
    # use_readline()
    # seek_start()
    # seek_b_cur()
    # copy_file()
    # modify_movie()
    # use_rename()
    # use_dir_func()
    scan_dir('.', 0)
